from sqlalchemy.future import select
from sqlalchemy import update as sql_update

from app.config import db, commit_rollback
from app.model.news import News  # Import your News model
from app.repository.base_repo import BaseRepo

class NewsRepository(BaseRepo):
    model = News  # Set the model to your News model

    @staticmethod
    async def find_by_id(news_id: int):
        query = select(News).where(News.id == news_id)
        return (await db.execute(query)).scalar_one_or_none()

    @staticmethod
    async def find_by_url(url: str):
        query = select(News).where(News.url == url)
        return (await db.execute(query)).scalar_one_or_none()

    @staticmethod
    async def add_news(news_data: dict):
        # 检查数据库中是否已存在具有相同URL的新闻项
        existing_news = await NewsRepository.find_by_url(news_data["url"])

        # 如果存在相同URL的新闻项，则跳过插入操作
        if existing_news:
            return False
        # 创建一个新的 News 对象并添加到数据库
        news = News(**news_data)
        db.add(news)
        await commit_rollback()
        return True  # 返回添加的新闻对象